package plugin

import (
	"distribute-mapreduce/common/mrtype"
	"github.com/sirupsen/logrus"
	"os"
	"plugin"
)

// LoadPlugin loads the application Map and Reduce functions
// from a plugin file, e.g. ../mrapps/wc.so
func LoadPlugin(filename string) (func(string, string) []mrtype.KeyValue, func(string, []string) string) {
	p, err := plugin.Open(filename)
	if err != nil {
		dir, _ := os.Getwd()
		logrus.Fatalf("cannot load plugin %v, current dir = %v", filename, dir)
	}
	xmapf, err := p.Lookup("Map")
	if err != nil {
		logrus.Fatalf("cannot find Map in %v", filename)
	}
	mapf := xmapf.(func(string, string) []mrtype.KeyValue)
	xreducef, err := p.Lookup("Reduce")
	if err != nil {
		logrus.Fatalf("cannot find Reduce in %v", filename)
	}
	reducef := xreducef.(func(string, []string) string)

	return mapf, reducef
}
